package com.guguskins.back.common.schedules;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.guguskins.back.entity.GuGoods;
import com.guguskins.back.entity.GuSystemConfig;
import com.guguskins.back.entity.dto.Item;
import com.guguskins.back.service.GuGoodsService;
import com.guguskins.back.service.GuSystemConfigService;
import com.guguskins.back.utils.CommonUtil;
import com.guguskins.back.utils.SendMailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author duttonliu
 * @date 2021/8/3 15:14
 */
@Component
@Slf4j
public class GuGoodsSchedule {

    @Autowired
    private GuGoodsService goodsService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private GuSystemConfigService systemConfigService;

    @Scheduled(cron = "0 0 0 */1 * ?")
    public void updateGoods() throws InterruptedException {
        int p = 1;
        int totalPage = 0;

        String cookie = systemConfigService.getSystemConfig().getConfigBuffCookie();
        cookie = cookie.replace("_gat_gtag_UA_109989484_1=1; ", "");
        do {
            long start = System.currentTimeMillis();
            Thread.sleep((int) (Math.random() * 15000 + 5000));
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cookie", cookie);
            HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
            ResponseEntity<JSONObject> resEntity = restTemplate.exchange("https://buff.163.com/api/market/goods?game=csgo&page_num=" + p + "&sort_by=price.desc&_=" + System.currentTimeMillis(), HttpMethod.GET, requestEntity, JSONObject.class);
            p++;
            if (!resEntity.getStatusCode().equals(HttpStatus.OK)) {
                SendMailUtil.sendSimpleMail("873402131@qq.com", "网易buff报错预警", resEntity.getBody().toJSONString());
                break;
            }
            JSONObject data = resEntity.getBody().getJSONObject("data");
            log.info("日志文件：{}", data);
            //设置goods属性
            List<Item> items = JSON.parseArray(data.getJSONArray("items").toJSONString(), Item.class);
            for (Item item : items) {
                GuGoods goods = new GuGoods();
                goods.setGoodsName(item.getName());
                goods.setGoodsShortName(item.getShortName());
                goods.setGoodsIconUrl(item.getGoodsInfo().getIconUrl());
                goods.setGoodsOriginalIconUrl(item.getGoodsInfo().getOriginalIconUrl());
                goods.setGoodsOriginalIconUrl(item.getGoodsInfo().getOriginalIconUrl());
                goods.setGoodsSellMinPrice(new BigDecimal(item.getSellMinPrice()));
                goods.setGoodsPrice(new BigDecimal(item.getSellMinPrice()));
                goods.setGoodsTagExterior(ObjectUtils.isEmpty(item.getGoodsInfo().getInfo().getTags().getExterior()) ? null : item.getGoodsInfo().getInfo().getTags().getExterior().getLocalizedName());
                goods.setGoodsTagType(item.getGoodsInfo().getInfo().getTags().getType().getLocalizedName());
                //查询只需要的饰品
                List<String> types = Arrays.asList("匕首", "微型冲锋枪", "手套", "手枪", "机枪", "步枪", "武器箱", "狙击步枪", "霰弹枪");
                if (!types.contains(goods.getGoodsTagType())) {
                    continue;
                }

                goods.setGoodsTagQuality(ObjectUtils.isEmpty(item.getGoodsInfo().getInfo().getTags().getQuality()) ? null : item.getGoodsInfo().getInfo().getTags().getQuality().getLocalizedName());
                goods.setGoodsTagWeapon(ObjectUtils.isEmpty(item.getGoodsInfo().getInfo().getTags().getWeapon()) ? null : item.getGoodsInfo().getInfo().getTags().getWeapon().getLocalizedName());
                goods.setGoodsTagRarity(ObjectUtils.isEmpty(item.getGoodsInfo().getInfo().getTags().getRarity()) ? null : item.getGoodsInfo().getInfo().getTags().getRarity().getLocalizedName());
                //设置饰品等级
                if (Arrays.asList("手套", "匕首").contains(goods.getGoodsTagType()) || goods.getGoodsName().contains("咆哮")) {
                    goods.setGoodsLevel(5);
                } else {
                    switch (goods.getGoodsTagRarity()) {
                        case "非凡":
                        case "违禁":
                            goods.setGoodsLevel(5);
                            break;
                        case "隐秘":
                            goods.setGoodsLevel(4);
                            break;
                        case "保密":
                        case "受限":
                            goods.setGoodsLevel(3);
                            break;
                        case "军规级":
                        case "工业级":
                            goods.setGoodsLevel(2);
                            break;
                        default:
                            goods.setGoodsLevel(1);
                    }
                }
                if (goodsService.count(new LambdaQueryWrapper<GuGoods>() {
                    {
                        eq(GuGoods::getGoodsShortName, goods.getGoodsShortName());
                    }
                }) > 0) {
                    goodsService.update(goods, new LambdaUpdateWrapper<GuGoods>() {
                        {
                            eq(GuGoods::getGoodsShortName, goods.getGoodsShortName());
                        }
                    });
                } else {
                    GuGoods guGoods = goodsService.getOne(new LambdaQueryWrapper<GuGoods>() {
                        {
                            eq(GuGoods::getGoodsShortName, goods.getGoodsShortName());
                        }
                    });
                    if (!ObjectUtils.isEmpty(guGoods)) {
                        goods.setGoodsSameId(guGoods.getGoodsSameId());
                    } else {
                        goods.setGoodsSameId(CommonUtil.generateRandomStr());
                    }
                    goods.insert();
                }
            }
            List<String> setCookies = resEntity.getHeaders().get("Set-Cookie");
            if (!CollectionUtils.isEmpty(setCookies)) {
                System.err.println(cookie);
                cookie= cookie.substring(0, cookie.lastIndexOf("session="));
                String session = setCookies.stream().filter(setCookie -> setCookie.contains("session=")).findFirst().orElse("").replaceAll("HttpOnly; Path=/", "");
                String csrfToken = setCookies.stream().filter(setCookie -> setCookie.contains("csrf_token=")).findFirst().orElse("").replaceAll("; Path=/", "");
                cookie += session + csrfToken;
                System.err.println("拼接：" + cookie);
            }
            System.err.println(p + "结果：" + resEntity.getStatusCode() + " 耗时：" + (System.currentTimeMillis() - start));
            if (totalPage == 0) {
                totalPage = data.getInteger("total_page");
            }
        } while (p <= totalPage);
        //
        GuSystemConfig systemConfig = new GuSystemConfig();
        systemConfig.setConfigBuffCookie(cookie);
        systemConfigService.backEdit(systemConfig);
    }
}
